package com.itheima.service;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import com.itheima.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return null;
    }

    @Override
    public Result register(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (null != user) {
            return Result.error("用户名已占用!");
        }
        User insertUser = new User();
        insertUser.setUsername(username);
        insertUser.setPassword(Md5Util.getMD5String(password));
        insertUser.setCreateTime(LocalDateTime.now());
        insertUser.setUpdateTime(LocalDateTime.now());
        Boolean isInsert = userMapper.insertUser(insertUser);
        if (!isInsert) {
            return Result.error("注册失败!");
        }
        return Result.success();
    }

    @Override
    public Result login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (null == user) {
            return Result.error("用户不存在!");
        }
        //验证密码是否正确
        if (!Md5Util.checkPassword(password, user.getPassword())) {
            return Result.error("密码错误!");
        }
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.genToken(claims);
        return Result.success(token);
    }

    @Override
    public Result getUserinfo() {
        //1.从threadLocal中获取登录用户信息
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userMapper.findByUsername(username);
        if (null == user) {
            return Result.error("获取用户信息失败!");
        }
        return Result.success(user);
    }

    @Override
    public Result updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());

        if (!ThreadLocalUtil.getUsername().equals(user.getUsername())) {
            return Result.error("操作异常,请退出系统重新登录!");
        }

        Boolean isUpdate = userMapper.updateByUsername(user);
        return Result.success(isUpdate);
    }

    @Override
    public Result logout() {
        //Map<String,Object> claims = ThreadLocalUtil.get();
        //ThreadLocalUtil.set(null);

        return Result.success("已退出!");
    }
}
